import React from 'react';
import axios from 'axios';
import './window.css';
import { Icon,Form,TextArea,Button } from 'semantic-ui-react'
import handle from './wsmain.js'
import IMEvent from './IMEvent.js'

class ChatWindow extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
       msgContent:'',
       listData:[],
       client:null
    }
  }

  componentDidMount() {
    const {from_user,to_user} = this.props.currentInfo;
    axios.post('chats/info',{
      from_user: from_user,
      to_user: to_user
    }).then(result=>{
      if(result.meta.status === 200) {
        var currentUser=localStorage.getItem('uid')
        var client=handle(currentUser,(data)=>{
            // 调用handle来建立webscoket链接，这个回调函数是接收到后台数据的时候调用
            this.setState({
                listData: [...this.state.listData,JSON.parse(data)]
            });
        })
        this.setState({
          listData: result.data.list,
          client
        });
      }
    })
  }

  sendMsg = () => {
    const {from_user, to_user, avatar} = this.props.currentInfo;
    let pdata = {
      id: new Date().getTime(), // 后台数据需要前端给一个自定义的id利用当前的时间来生成即可
      from_user: from_user,
      to_user: to_user,
      avatar: avatar,
      chat_msg: this.state.msgContent
    }
    this.state.client.emitEvent(IMEvent.MSG_TEXT_SEND,JSON.stringify(pdata)) // 给后台发送数据
    this.setState({
        listData:[...this.state.listData,pdata]
    })
  }
  handleMsgChange = (e) => {
    this.setState({
        msgContent:e.target.value
    })
  }

  render() {
    const {username} = this.props.currentInfo;
    //获取当前用户ID（用于判断当前聊天用户）
    let currentUser = parseInt(localStorage.getItem('uid'),10);
    const listContent = this.state.listData.map(item=>{
      return ( // 添加类名来把当前用户放在聊天框的右边，与之聊天的放在右边
        <li key={item.id} className={currentUser===item.from_user? 'chat-info-right':'chat-info-left'}>
          <img src={item.avatar.indexOf("public") !== -1 ?'http://127.0.0.1:8086/' + item.avatar : item.avatar} alt=""/>
          <span>{item.chat_msg}</span>
        </li>
      )
    })
    return (
      <div className='chat-window'>
        <div className="chat-window-title">
          <Icon onClick={this.props.hideChat} name='angle left' className='chat-ret-btn' size='large'/>
          <span>{username}</span>
        </div>
        <div className="chat-window-content">
          <ul>
              {listContent}
          </ul>
        </div>
        <div className="chat-window-input">
          <Form>
            <TextArea value={this.state.msgContent} onChange={this.handleMsgChange} placeholder='请输入内容...' />
            <Button onClick={this.props.hideChat}>关闭</Button>
            <Button primary onClick={this.sendMsg}>发送</Button>
          </Form>
        </div>
      </div>
    );
  }
}
export default ChatWindow;
